const fs = require('fs');
const path = require('path');
const http = require('http');
const server = http.createServer();

server.on('request',async (req,res)=>{
  const url = req.url;
  let content = '404 not found';
  if(url === '/clock/index.html' || url === '/clock/index.css' || url === '/clock/index.js'){
    content = await readFile(url)
  }
  // 如果用户不想输入clock
  if(url === '/index.html' || url === '/index.css' || url === '/index.js'){
    content = await readFile('/clock'+url)
  }
  res.setHeader('Content-type','text/html;charset=utf-8')
  res.end(content)
})

server.listen('8080',()=>{
  console.log('server run in http://127.0.0.1')
})

function readFile(url){
  return new Promise((resolve,reject)=>{
    fs.readFile(path.join(__dirname,url),'utf-8',(err,dataStr)=>{
      if(err){
        reject()
        return
      }
      resolve(dataStr)
    })
  })
}